package com.qf.petmall.starter.login.controller;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qf.petmall.starter.login.CreateTooken;
import com.qf.petmall.starter.login.entity.Users;
import com.qf.petmall.starter.login.service.IUsersService;
import com.qf.petmall.starter.utils.R;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.scope.*;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.*;
import me.zhyd.oauth.utils.AuthScopeUtils;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2019/2/19 9:28
 * @since 1.8
 */
@Slf4j
@CrossOrigin
@Controller
@RequestMapping("/oauth")
public class RestAuthController {

    @Autowired
    IUsersService iUsersService;
    // source 代表三方平台，例如 gitee，qq，微信等
    // 如果只做gitee可以不传
    @RequestMapping("/render/{source}")
    @ResponseBody
    public void renderAuth(@PathVariable("source") String source, HttpServletResponse response,HttpServletRequest request) throws IOException {

        StringBuffer requestURL = request.getRequestURL();
        log.info("进入render：" + source);
        AuthRequest authRequest = getAuthRequest(source);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info(authorizeUrl);
        response.sendRedirect(authorizeUrl);
    }

    /**
     * oauth平台中配置的授权回调地址，以本项目为例，在创建github授权应用时的回调地址应为：http://127.0.0.1:8443/oauth/callback/github
     */
    @RequestMapping("/callback/{source}")
    public ModelAndView login(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request) throws JsonProcessingException {

        log.info("进入callback：" + source + " callback params：" + JSONObject.toJSONString(callback));
        AuthRequest authRequest = getAuthRequest(source);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        log.info(JSONObject.toJSONString(response));

        if (response.ok()) {
            // 保存用户的登录状态，单节点到session中，微服务到 redis中
            AuthUser data = response.getData();
            String avatar = data.getAvatar();
            String username = data.getUsername();
            LambdaQueryWrapper<Users> usersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            usersLambdaQueryWrapper.eq(Users::getUsername,username);
            Users one = iUsersService.getOne(usersLambdaQueryWrapper);
            if(one==null){
                Users users=new Users();
                users.setUserImg(avatar);
                users.setUsername(username);
                iUsersService.save(users);
                String token = CreateTooken.createToken(users);
                ModelAndView modelAndView = new ModelAndView("redirect:http://192.168.20.65:5173/home?token="+token);
//                ModelAndView modelAndView = new ModelAndView("http://www.baidu.com");
                return modelAndView;
            }else {
                String token = CreateTooken.createToken(one);
                ModelAndView modelAndView = new ModelAndView("redirect:http://192.168.20.65:5173/home?token="+token);
//                ModelAndView modelAndView = new ModelAndView("http://www.baidu.com");
                return modelAndView;
            }

            /*  userService.save(response.getData());*/

            // 根据需求考虑是否进行用户信息持久化到关系数据库中
            // 如果需要把 三方用户信息保存到本地数据库，则进行持久化，注意每个用户名只需要进行一次即可


        }

        Map<String, Object> map = new HashMap<>(1);
        map.put("errorMsg", response.getMsg());

        return new ModelAndView("error", map);
    }

    private AuthRequest getAuthRequest(String source) {
        AuthRequest authRequest = null;
        switch (source.toLowerCase()) {
            case "weibo":
                authRequest = new AuthWeiboRequest(AuthConfig.builder()
                        .clientId("")
                        .clientSecret("")
                        .redirectUri("http://dblog-web.zhyd.me/oauth/callback/weibo")
                        .scopes(Arrays.asList(
                                AuthWeiboScope.EMAIL.getScope(),
                                AuthWeiboScope.FRIENDSHIPS_GROUPS_READ.getScope(),
                                AuthWeiboScope.STATUSES_TO_ME_READ.getScope()
                        ))
                        .build());
                break;
            case "gitee":
                authRequest = new AuthGiteeRequest(AuthConfig.builder()
                        .clientId("f2d15ea16e39475be0cc2c510b965d1519127b9d68705b774292e804688c2c73")
                        .clientSecret("fe82b989208592286429a3a04908823c565d32c336e70e7bed0fd6eeee61de20")
                        .redirectUri("http://192.168.10.81:8878/oauth/callback/gitee")
//                        .scopes(AuthScopeUtils.getScopes(AuthGiteeScope.values()))
                        .scopes(AuthScopeUtils.getScopes(AuthGiteeScope.USER_INFO))
                        .build());
                break;
            case "qq":
                authRequest = new AuthQqRequest(AuthConfig.builder()
                        .clientId("")
                        .clientSecret("")
                        .redirectUri("http://localhost:8443/oauth/callback/qq")
                        .build());
                break;
        }
        if (null == authRequest) {
            throw new AuthException("未获取到有效的Auth配置");
        }
        return authRequest;
    }


}